// Agent maintainer in project EMarket

/* Initial beliefs and rules */

/* Initial goals */

!start.

/* Plans */

+!start : true <- 
	.print("Maintainer started").
	
	
	
/* Goals */
+!requestOffers(Item)[source(Buyer)] : true <-
	+waitingForOffers( Item, Buyer );
	.print( "New goal: requestOffers(", Item, ") for Buyer ", Buyer );
	registerNewRequest( Item, Buyer );
	makeMatchForRequest( Item, Buyer ); /* ask env. */
	.	
	
+!registerNewOffer( Item, Seller ) : true <-
	registerNewOffer( Item, Seller );	/* write in env. */
	makeMatchForOffer( Item, Seller );	/* ask for affected requests */
	.		





/* Updates from the environment */

/*
+newMatchForRequest( Buyer, Item, Sellers )[source(percept)] : waitingForOffers( Item, Buyer ) <-
	.print("Received newMatch ", Buyer, ", ", Item, ", ", Sellers );
	.send( Buyer, tell, newMatch(Item, Sellers) );
	-waitingForOffers( Item, Buyer ).
	

+newOfferForBuyers( Seller, Item, Buyers )[source(percept)] : true <- 
	.print("Update for Buyers ", Buyers, " wanting item: ", Item );
	for( .member( Buyer, Buyers ) )
	{
		.send( Buyer, tell, hasItem( Item, Seller) );
	};
	.
*/
	
	
+newMatch( Buyer, Item, Sellers )[source(percept)] : true <-		/* Gets called by the env. multiple times, per Buyer */
	.print( "newMatch ", Buyer, ", ", Item, ", ", Sellers );
	for( .member( Seller, Sellers ) )
	{
		.send( Buyer, tell, hasItem( Item, Seller ) );
	};
	.send( Buyer, tell, sellersComplete( Item ) );
	.	
	
	
	
	
/* Updates from traders */

+newOffer(Item)[source(Seller)] <-
	.print( "Registering new Offer ", Item, " for seller ", Seller );
	!registerNewOffer( Item, Seller ).
	
	
+!itemSold( Item, Buyer)[source( Seller )] : true <- 	/* TODO: Keep track of offers, so check here for consistency? */
	itemSold( Item, Buyer, Seller );
	.send( Buyer, tell, itemBought( Item, Seller ) );
	.
	